var __extends =
  (this && this.__extends) ||
  (function () {
    var a =
      Object.setPrototypeOf ||
      ({ __proto__: [] } instanceof Array &&
        function (e, c) {
          e.__proto__ = c;
        }) ||
      function (f, c) {
        for (var e in c) {
          if (c.hasOwnProperty(e)) {
            f[e] = c[e];
          }
        }
      };
    return function (f, c) {
      a(f, c);
      function e() {
        this.constructor = f;
      }
      f.prototype = c === null ? Object.create(c) : ((e.prototype = c.prototype), new e());
    };
  })();
var Chivox;
(function (b) {
  var c = (function () {
    function d() {}
    d.prototype.isUrl = function (e) {
      var k = "((https?|http):\\/\\/)?";
      var n = "([a-z0-9\\d-_]\\w*(\\:[\\S]+)?\\@)?";
      var g = "([a-zA-Z\\d][a-zA-Z\\d-_]+.)+[a-zA-Z\\d-_][^ ]*";
      var f = "(:\\d{1,5})?";
      var i = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
      var l = "(\\/\\S*)?";
      var m = [k, g, f, l];
      var h = [k, i, f, l];
      var j = function (o) {
        return new RegExp("^" + o.join("") + "$", "i").test(e);
      };
      return j(m) || j(h);
    };
    d.prototype.generateGuid = function () {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (g) {
        var f = (Math.random() * 16) | 0,
          e = g === "x" ? f : (f & 3) | 8;
        return e.toString(16);
      });
    };
    d.prototype.generateTimestamp = function () {
      return parseInt((new Date().getTime() / 1000).toString());
    };
    d.prototype.getScript = function (g) {
      var f = document.getElementsByTagName("head").item(0);
      var e = document.createElement("script");
      e.type = "text/javascript";
      e.src = g;
      f.appendChild(e);
    };
    return d;
  })();
  b.Utils = c;
  var a;
  (function (d) {
    d[(d["Starting"] = 0)] = "Starting";
    d[(d["Recording"] = 1)] = "Recording";
    d[(d["Completed"] = 2)] = "Completed";
  })((a = b.Status || (b.Status = {})));
})(Chivox || (Chivox = {}));
var Chivox;
(function (c) {
  var a = (function () {
    function e() {
      this._utils = new c.Utils();
      this._host = "https://api.chivoxapp.com";
      this._route = "cgi-bin";
      this._version = 16909572;
      this._results = {};
      this._voices = {};
      this._status = c.Status.Completed;
      this._startTime = 0;
      this._endTime = 0;
      this._lastVoice = { localId: "", startTime: 0, endTime: 0, duration: 0, tokenId: "" };
      this._relaxation_factor = 0;
      this._httpClient = new d();
      this._ensureAvailable = true;
      if ("undefined" === typeof wx) {
      }
    }
    Object.defineProperty(e.prototype, "utils", {
      get: function () {
        return this._utils;
      },
      enumerable: true,
      configurable: true,
    });
    Object.defineProperty(e.prototype, "version", {
      get: function () {
        var g = (this._version & 4278190080) >> 24;
        var f = "";
        f += g.toString();
        g = (this._version & 16711680) >> 16;
        f += "." + g.toString();
        g = (this._version & 65280) >> 8;
        f += "." + g.toString();
        g = this._version & 255;
        if (g !== 0) {
          f += "." + g.toString();
        }
        return f;
      },
      enumerable: true,
      configurable: true,
    });
    e.prototype.aiengine_new = function (f) {
      var g = this;
      if (f.gray) {
        g._route = "gray";
      }
      if (f.relaxation_factor && typeof f.relaxation_factor == "number") {
        this._relaxation_factor = f.relaxation_factor >= 0.5 && f.relaxation_factor <= 2 ? f.relaxation_factor : 0;
      }
      g.restData();
      if (typeof f.url !== "string" && !f.hasOwnProperty("signature")) {
        g.onError({ errId: 71001, error: "invalid url" }, f);
        return;
      }
      g._httpClient = new d(f.serverTimeout);
      g._ensureAvailable = typeof f.ensureAvailable === "boolean" ? f.ensureAvailable : g._ensureAvailable;
      if (g._ensureAvailable) {
        g.ensureNativeApiAvailable(f);
      } else {
        g.generateSignature(f.url, f);
      }
    };
    e.prototype.restData = function () {
      this._status = c.Status.Completed;
      this._endTime = 0;
      this._param = undefined;
    };
    e.prototype.ensureNativeApiAvailable = function (f) {
      var g = this;
      wx.ready(function () {
        wx.checkJsApi({
          jsApiList: ["startRecord", "stopRecord", "uploadVoice"],
          success: function (k) {
            if (k.errMsg === "checkJsApi:ok") {
              var j = typeof k.checkResult === "string" ? JSON.parse(k.checkResult) : k.checkResult;
              if ("undefined" === typeof j.startRecord || j.startRecord === false) {
                g.onError({ errId: 71032, error: "pre-authorize fail: startRecord:permission denied. please check jsApiList in wx.config fun." }, f);
                return;
              }
              if ("undefined" === typeof j.stopRecord || j.stopRecord === false) {
                g.onError({ errId: 71033, error: "pre-authorize fail: stopRecord:permission denied. please check jsApiList in wx.config fun." }, f);
                return;
              }
              if ("undefined" === typeof j.uploadVoice || j.uploadVoice === false) {
                g.onError({ errId: 71034, error: "pre-authorize fail: uploadVoice:permission denied. please check jsApiList in wx.config fun." }, f);
                return;
              }
              var i = 450;
              var h = 600;
              f.preAuthorize = typeof f.preAuthorize !== "number" ? i : f.preAuthorize;
              f.preAuthorize = f.preAuthorize < i && f.preAuthorize !== 0 ? i : f.preAuthorize;
              f.preAuthorize = f.preAuthorize > h ? h : f.preAuthorize;
              if (f.preAuthorize > 0) {
                g.ensurePreAuthorize(f);
              } else {
                g.generateSignature(f.url, f);
              }
            } else {
              g.onError({ errId: 71035, error: "pre-authorize fail: api unauthorized. please check jsApiList in wx.config fun." }, f);
            }
          },
        });
      });
    };
    e.prototype.ensurePreAuthorize = function (f) {
      var g = this;
      wx.ready(function () {
        wx.startRecord({
          success: function () {
            setTimeout(function () {
              wx.stopRecord({
                success: function (h) {
                  wx.uploadVoice({
                    localId: h.localId,
                    isShowProgressTips: 0,
                    success: function (i) {
                      g.generateSignature(f.url, f);
                    },
                    fail: function (i) {
                      g.onError({ errId: 71034, error: "pre-authorize fail: " + i.errMsg }, f);
                    },
                  });
                },
                fail: function (h) {
                  if (h.errMsg !== "stopRecord:tooshort") {
                    g.onError({ errId: 71033, error: "pre-authorize fail: " + h.errMsg }, f);
                  } else {
                    g.generateSignature(f.url, f);
                  }
                },
              });
            }, f.preAuthorize);
          },
          fail: function (h) {
            g.onError({ errId: 71032, error: "pre-authorize fail: " + h.errMsg }, f);
          },
          cancel: function (h) {
            g.onError({ errId: 71036, error: "pre-authorize fail: " + h.errMsg }, f);
          },
        });
      });
    };
    e.prototype.generateSignature = function (g, f) {
      var h = this;
      if (f.hasOwnProperty("signature")) {
        var i = f.signature;
        if (!h.invalidSignature(i, f)) {
          return;
        }
        i.version = h._version;
        h.getJwtToken(i, f);
      } else {
        h._httpClient.Post({
          url: g,
          success: function (j) {
            if (typeof j === "undefined" || typeof j.data !== "object") {
              h.onError({ errId: 71005, error: "response data not object. please check signature service on '" + g + "' " }, f);
            } else {
              var k = j.data;
              if (!h.invalidSignature(k, f)) {
                return;
              }
              k.version = h._version;
              h.getJwtToken(k, f);
            }
          },
          fail: function (k, j) {
            h.onError({ errId: 71009, error: "request signature service fail ;status:" + k.status + ";message:" + j.message }, f);
          },
        });
      }
    };
    e.prototype.getJwtToken = function (h, f) {
      var g = this;
      g._httpClient.Post({
        url: g._host + "/" + g._route + "/get_token",
        content: h,
        success: function (j) {
          if (typeof j === "undefined" || typeof j.data !== "object") {
            g.onError({ errId: 71010, error: "request token service with invalid data" }, f);
          } else {
            if (!g.validate(j.data, f)) {
              var i = j.data;
              if (typeof i.access_token !== "string" || i.access_token.split(".").length !== 3) {
                g.onError({ errId: 71013, error: "invalid token for access_token" }, f);
                return;
              }
              if (typeof i.token_type !== "string") {
                g.onError({ errId: 71014, error: "invalid token for token_type" }, f);
                return;
              }
              g._token = i;
              if (typeof f.success === "function") {
                f.success();
              }
              if (typeof f.complete === "function") {
                f.complete();
              }
            }
          }
        },
        fail: function (j, i) {
          g.onError({ errId: 71011, error: "request token service fail :" + i.message }, f);
        },
      });
    };
    e.prototype.invalidSignature = function (h, f) {
      var g = this;
      if (!h || typeof h !== "object") {
        g.onError({ errId: 71005, error: "signature is not object. please check signature: '" + JSON.stringify(h) + "' " }, f);
        return false;
      }
      if (typeof h.appId !== "string" || typeof h.signature !== "string" || typeof h.timestamp !== "number") {
        g.onError({ errId: 71005, error: "signature data format is invalid. please check signature service on '" + JSON.stringify(h) + "' " }, f);
        return false;
      }
      if (h.appId.length !== 18) {
        g.onError({ errId: 71006, error: "invalid appId" }, f);
        return false;
      }
      if (h.signature.length !== 40) {
        g.onError({ errId: 71007, error: "invalid signature" }, f);
        return false;
      }
      if (h.timestamp.toString().length !== 10) {
        g.onError({ errId: 71008, error: "invalid timestamp" }, f);
        return false;
      }
      return true;
    };
    e.prototype.aiengine_start = function (g) {
      var f = this;
      if (typeof f._token === "undefined") {
        f.onError({ errId: 71029, error: "must aiengine_new success first" }, g);
        return;
      }
      if (f._status !== c.Status.Completed) {
        f.onError({ errId: 71018, error: "the task has runing, please wait stop" }, g);
        return;
      }
      f._status = c.Status.Recording;
      if (typeof g.request.coreType !== "string" || g.request.coreType.length === 0) {
        f.onError({ errId: 71020, error: "invalid coreType" }, g);
        return;
      }
      if (typeof g.request.refText !== "string" && typeof g.request.refText !== "object") {
        f.onError({ errId: 71021, error: "invalid refText" }, g);
        return;
      }
      if (typeof g.request.tokenId !== "string" || g.request.tokenId === "") {
        g.request.tokenId = f._utils.generateGuid().replace(/-/g, "");
      }
      f._startTime = f._utils.generateTimestamp();
      f.startRecord(g);
    };
    e.prototype.startRecord = function (g) {
      var f = this;
      wx.ready(function () {
        wx.startRecord({
          success: function (h) {
            f._param = g;
          },
          fail: function (h) {
            f.onError({ errId: 71023, error: "invoke wx api startRecord fail: " + h.errMsg }, g);
          },
          cancel: function (h) {
            f.onError({ errId: 71036, error: "invoke wx api startRecord fail: " + h.errMsg }, g);
          },
        });
      });
    };
    e.prototype.uploadFile = function (g, f, i) {
      var h = this;
      wx.ready(function () {
        wx.uploadVoice({
          localId: f.localId,
          isShowProgressTips: i.isShowProgressTips,
          success: function (j) {
            f.serverId = j.serverId;
            h._httpClient.Post({
              url: h._host + "/" + h._route + "/eval_gzh?serverId=" + f.serverId,
              authorization: g.token_type + " " + g.access_token,
              content: i.request,
              success: function (k) {
                if (typeof k === "undefined") {
                  h.onError({ errId: 71031, error: "invalid callback data" }, i);
                } else {
                  var l = k.data;
                  if (!h.validate(l, i)) {
                    if (typeof l.result !== "object" || typeof l.applicationId !== "string" || typeof l.tokenId !== "string") {
                      h.onError({ errId: 71024, error: "invalid json result" }, i);
                      return;
                    }
                    if (l.tokenId !== i.request.tokenId) {
                      h.onError({ errId: 71025, error: "tokenId not match" }, i);
                      return;
                    }
                    if (h._relaxation_factor === 0 || l.error) {
                      h._results[l.tokenId] = l;
                    } else {
                      l = h.relaxationFactor(l);
                      h._results[l.tokenId] = l;
                    }
                    if (typeof i.success === "function") {
                      i.success(l);
                    }
                    if (typeof i.complete === "function") {
                      i.complete(f);
                    }
                    h.restData();
                  }
                }
              },
              fail: function (l, k) {
                h.onError({ errId: 71041, error: "request eval api fail :" + k.message }, i);
              },
            });
          },
          fail: function (j) {
            h.onError({ errId: 71039, error: "invoke wx api uploadVoice fail: " + j.errMsg }, i);
          },
        });
      });
    };
    e.prototype.aiengine_stop = function (f) {
      var g = this;
      if (typeof g._token === "undefined") {
        g.onError({ errId: 71029, error: "must aiengine_new success first" }, f);
        return;
      }
      if (g._status !== c.Status.Recording) {
        g.onError({ errId: 71038, error: "must aiengine_start success first" }, f);
        return;
      }
      g._endTime = g._utils.generateTimestamp();
      g.stopRecord(f);
    };
    e.prototype.stopRecord = function (f) {
      var g = this;
      wx.ready(function () {
        wx.stopRecord({
          success: function (h) {
            if (typeof g._param !== "object") {
              g.onError({ errId: 71038, error: "must aiengine_start success first" }, f);
              return;
            }
            if (typeof h === "undefined" || typeof h.localId === "undefined") {
              g.onError({ errId: 71030, error: "invalid record data" }, g._param);
              return;
            }
            g._lastVoice = {
              localId: h.localId,
              tokenId: g._param.request.tokenId,
              startTime: g._startTime,
              endTime: g._endTime,
              duration: g._endTime - g._startTime,
            };
            g._voices[g._lastVoice.tokenId] = g._lastVoice;
            g.uploadFile(g._token, g._lastVoice, g._param);
            if (typeof f.success === "function") {
              f.success();
            }
            if (typeof f.complete === "function") {
              f.complete();
            }
          },
          fail: function (h) {
            g.onError({ errId: 71028, error: "invoke wx api stopRecord fail: " + h.errMsg }, f);
          },
        });
      });
    };
    e.prototype.getResult = function (f) {
      return this._results[f];
    };
    e.prototype.getVoice = function (f) {
      if (typeof f === "string") {
        return this._voices[f];
      } else {
        return this._lastVoice;
      }
    };
    e.prototype.getPinYin = function (f) {
      var g = this;
      if (typeof g._token === "undefined") {
        g.onError({ errId: 71029, error: "must aiengine_new success first" }, f);
      } else {
        g._httpClient.Post({
          url: g._host + "/" + g._route + "/get_pinyin",
          authorization: g._token.token_type + " " + g._token.access_token,
          content: { reftext: f.reftext },
          success: function (h) {
            if (typeof h === "undefined" || typeof h.data !== "object") {
              g.onError({ errId: 71039, error: "request pinyin api service with invalid data" }, f);
            } else {
              if (!g.validate(h.data, f)) {
                if (typeof f.success === "function") {
                  f.success(h.data);
                }
                if (typeof f.complete === "function") {
                  f.complete(h.data);
                }
              }
            }
          },
          fail: function () {
            g.onError({ errId: 71040, error: "request pinyin api service fail" }, f);
          },
        });
      }
    };
    e.prototype.onError = function (g, f) {
      if (typeof f.fail === "function") {
        f.fail(g);
      }
      if (typeof f.complete === "function") {
        f.complete(g);
      }
      this.restData();
    };
    e.prototype.validate = function (h, g) {
      var f = typeof h.errId === "number" && typeof h.error === "string" && typeof h.dtLastResponse === "string" && typeof h.eof === "number";
      if (f) {
        this.onError(h, g);
      }
      return f;
    };
    e.prototype.relaxationFactor = function (f) {
      switch (f.params.request.coreType) {
        case "en.word.score":
        case "en.word.child":
          f = this.enWordDetail(f);
          break;
        case "en.sent.score":
        case "en.sent.child":
          f = this.enSentDetail(f);
          break;
        case "en.pred.exam":
          f = this.enPredDetail(f);
          break;
        default:
          f = f;
      }
      return f;
    };
    e.prototype.enWordDetail = function (k) {
      if (!k.hasOwnProperty("result")) {
        return k;
      }
      var h = k.result;
      var g = h.overall * this._relaxation_factor;
      var j = g >= 100 ? 100 : g;
      h.overall = j;
      if (h.hasOwnProperty("accuracy")) {
        var f = h.accuracy * this._relaxation_factor;
        var l = f >= 100 ? 100 : f;
        h.accuracy = l;
      }
      var i = ["accuracy", "fluency", "integrity", "rhythm"];
      if (j > 80) {
        h = this.setDetailsMax(i, h, j);
      }
      if (j < 54) {
        h = this.setDetailsMin(i, h, j);
      }
      k.result = h;
      return k;
    };
    e.prototype.enSentDetail = function (k) {
      if (!k.hasOwnProperty("result")) {
        return k;
      }
      var g = k.result;
      var i = g.overall * this._relaxation_factor;
      var j = i >= 100 ? 100 : i;
      g.overall = j;
      var f = g.accuracy * this._relaxation_factor;
      var l = f >= 100 ? 100 : f;
      g.accuracy = l;
      var h = ["accuracy", "fluency", "integrity", "rhythm"];
      if (j > 80) {
        g = this.setDetailsMax(h, g, j);
      }
      if (j < 54) {
        g = this.setDetailsMin(h, g, j);
      }
      k.result = g;
      return k;
    };
    e.prototype.enPredDetail = function (l) {
      if (!l.hasOwnProperty("result")) {
        return l;
      }
      var f = l.result;
      var j = f.overall * this._relaxation_factor;
      var k = j >= 100 ? 100 : j;
      f.overall = k;
      var i = f.pron * this._relaxation_factor;
      var h = i >= 100 ? 100 : i;
      f.pron = h;
      var g = ["pron", "fluency", "integrity", "rhythm"];
      if (k > 80) {
        l.result = this.setDetailsMax(g, f, k);
      }
      if (k < 54) {
        l.result = this.setDetailsMin(g, f, k);
      }
      return l;
    };
    e.prototype.setDetailsMin = function (g, f, h) {
      if (g && Array.isArray(g)) {
        g.forEach(function (j, i) {
          if (f.hasOwnProperty(j) && typeof f[j] == "string") {
            f[j] = f[j] > h ? h : f[j];
          } else {
            if (f.hasOwnProperty(j) && typeof f[j] == "object") {
              f[j].overall = f[j].overall > h ? h : f[j].overall;
            }
          }
        });
      }
      return f;
    };
    e.prototype.setDetailsMax = function (g, f, h) {
      if (g && Array.isArray(g)) {
        g.forEach(function (j, i) {
          if (f.hasOwnProperty(j) && typeof f[j] != "object") {
            f[j] = f[j] < 80 ? 80 : f[j];
          } else {
            if (f.hasOwnProperty(j) && typeof f[j] == "object") {
              f[j].overall = f[j].overall < 80 ? 80 : f[j].overall;
            }
          }
        });
      }
      return f;
    };
    return e;
  })();
  c.AiEngine = a;
  var d = (function () {
    function e(f) {
      this._timeout = typeof f === "undefined" ? 50 : f;
    }
    e.prototype.Post = function (f) {
      this.xhr("POST", f.url, f.authorization, f.content, f.success, f.fail);
    };
    e.prototype.xhr = function (l, g, h, i, k, f) {
      var j = new XMLHttpRequest();
      j.timeout = this._timeout * 1000;
      j.open(l, g, true);
      j.setRequestHeader("X-Requested-With", "XMLHttpRequest");
      j.setRequestHeader("Content-Type", "application/json; charset=utf-8");
      if (h) {
        j.setRequestHeader("Authorization", h);
      }
      j.send(JSON.stringify(i));
      j.onload = function () {
        if (j.status >= 200 && j.status < 300) {
          if (k) {
            if (typeof j.response === "string") {
              var m = { data: JSON.parse(j.response) };
              k(m, j.status, j);
            } else {
              if (f) {
                f(j, new b(j.statusText, j.status));
              }
            }
          }
        } else {
          if (f) {
            f(j, new b(j.statusText, j.status));
          }
        }
      };
      j.onabort = function () {
        if (f) {
          f(j, new b("request abort", j.status));
        }
      };
      j.onerror = function () {
        if (f) {
          f(j, new b(j.statusText, j.status));
        }
      };
      j.ontimeout = function () {
        if (f) {
          f(j, new b("request timeout", j.status));
        }
      };
    };
    return e;
  })();
  var b = (function (f) {
    __extends(e, f);
    function e(g, h) {
      var i = f.call(this, g) || this;
      i.statusCode = h;
      return i;
    }
    return e;
  })(Error);
})(Chivox || (Chivox = {}));
var aiengine = new Chivox.AiEngine();
